﻿using System;
using System.Linq;
using LazyLoad.Model;
using NUnit.Framework;
using Xtensive.Orm;
using Xtensive.Orm.Configuration;
using Xtensive.Orm.Providers;
using Xtensive.Orm.Services;

namespace LazyLoad
{
    public class Program
    {
        [Test]
        public static void Main()
        {
            // Loading domain configuration section with name "Default".
            var domainConfiguration = DomainConfiguration.Load("Default");
            var domain = Domain.Build(domainConfiguration);

            using (var session = domain.OpenSession()) {
                using (var t = session.OpenTransaction()) {
                    var article = new Article(session) {
                        Title = "DataObjects.Net unleashed",
                        Content = @"
DataObjects.Net is the ideal object-relational mapper (ORM) and business logic layer (BLL) development framework for modern .NET projects that:
Wish to leverage all the best language features and technologies that .NET has to offer
- Have non-trivial domain models with deep inheritance and composite objects
- Prefer code-first, test-driven development
- Cannot settle for less than excellent performance
- Want a solution that scales easily"
                    };

                    t.Complete();
                }

                using (var tx = session.OpenTransaction()) {
                    // Fetching article instance
                    var article = session.Query.All<Article>().First();

                    // Using a service to check the state of persistent fields
                    var accessor = DirectStateAccessor.Get(article);
                    Console.WriteLine("Field '{0}' is loaded? {1}", "Title", accessor.GetFieldState("Title").HasFlag(PersistentFieldState.Loaded));
                    Console.WriteLine("Field '{0}' is loaded? {1}", "Content", accessor.GetFieldState("Content").HasFlag(PersistentFieldState.Loaded));

                    // Accessing the 'Content' field directly. This will load the field value by separate query
                    int length = article.Content.Length;
                    Console.WriteLine("Field '{0}' is loaded? {1}", "Content", accessor.GetFieldState("Content").HasFlag(PersistentFieldState.Loaded));

                    tx.Complete();
                }
            }
        }
    }
}
